package com.tianming.boot62.controller;

import com.tianming.boot62.entity.User;
import com.tianming.boot62.entity.Weibo;
import com.tianming.boot62.mapper.WeiboMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper weiboMapper;

    @RequestMapping("/send")
    public int send(Weibo weibo, MultipartFile pic, HttpSession session) throws IOException {
        User user = (User) session.getAttribute("user");
        if (user==null) {
            return 0;
        }

        String fileName = pic.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffix;
        String dirPath = "d:/upload";
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String filePath = dirPath + "/" +fileName;
        pic.transferTo(new File(filePath));

        weibo.setUrl(fileName);
        weibo.setUserId(user.getId());
        weibo.setAuthor(user.getUsername());

        weiboMapper.insert(weibo);
        return 1;
    }
    @RequestMapping("/select")
    public List<Weibo> select(){
        return weiboMapper.select();
    }
    @RequestMapping("/selectmyweibo")
    public List<Weibo> selectMyWeibo(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user == null){
            return null;
        }
        return weiboMapper.selectmyweibo(user);
    }
    @RequestMapping("/delete")
    public void delete(int id){
        weiboMapper.delete(id);
    }
}
